package com.leo.tool.serialize.jdk;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import lombok.Cleanup;
import lombok.SneakyThrows;

/**
 * <li>目标需实现Serializable</li>
 * <li>static变量不参与序列化</li>
 * <li>transient变量不参与序列化</li>
 * <li>父类未实现Serializable变量不参与序列化，实现则参与</li>
 * 
 * @author Leo
 * @date 2019/06/30
 */
public class JdkSerializer {

    @SneakyThrows
    public static byte[] serialize(Object obj) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream outputStream = new ObjectOutputStream(baos);
        outputStream.writeObject(obj);
        outputStream.flush();
        return baos.toByteArray();
    }

    @SneakyThrows
    public static void serialize(String path, Object obj) {
        @Cleanup
        ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(path));
        outputStream.writeObject(obj);
        outputStream.flush();
    }

    @SuppressWarnings("unchecked")
    @SneakyThrows
    public static <T> T deserialize(byte[] bytes) {
        return (T)new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
    }

    @SuppressWarnings("unchecked")
    @SneakyThrows
    public static <T> T deserialize(String path) {
        @Cleanup
        ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(path));
        return (T)inputStream.readObject();
    }

}
